package com.qf.service.impl;

import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.domain.Order;
import com.qf.domain.User;
import com.qf.service.OrderService;
import com.qf.service.UserService;
import com.qf.utils.MD5Util;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao=new UserDaoImpl();
    @Override
    public boolean checkUserName(String username) {
        User user=userDao.selectByUsername(username);
        if(user!=null){
            return true;
        }
        return false;
    }

    @Override
    public void register(User user) {
        user.setPassword(MD5Util.md5(user.getPassword()));

        userDao.insert(user);
    }

    @Override
    public User login(String username, String password) {
        password=MD5Util.md5(password);
        User user=userDao.login(username,password);

        if(user==null){
            throw new RuntimeException("用户名不存在");
        }
        if(!user.getPassword().equalsIgnoreCase(password)){
            throw new RuntimeException("密码错误");
        }
        if(user.getFlag()!=1){
            throw new RuntimeException("账户未激活或激活已过期");
        }
        return user;
    }

    @Override
    public List<User> selectByRole() {
        return userDao.findByRole();
    }

    @Override
    public List<User> selectByNameAndGender(String where, List<Object> params) {
        //System.out.println(userDao.findByNameAndGender(where ,params));
        return userDao.findByNameAndGender(where ,params);
    }

    @Override
    public void deleteById(int uid) {
        OrderService orderService=new OrderServiceImpl();
        List<Order> orderList = orderService.selectByUserId(uid);
        System.out.println("orderList = " + orderList);
        if(orderList!=null&&orderList.size()>0){
            for (Order order : orderList) {
                 userDao.deleteBydetail(order.getId());
                 if(order==null){
                     userDao.removeByUId(uid);
                 }
            }
        }
        userDao.removeByUId(uid);
    }

    @Override
    public User selectByUId(Integer uid) {
        return userDao.findByUId(uid);
    }

    @Override
    public List<User> selectNoByNameAndGender(String where, List<Object> params) {
        return userDao.findNoByNameAndGender(where ,params);
    }

    @Override
    public void updateFlag1ById(int uid) {
        userDao.modifyFlag1ById(uid);
    }

    @Override
    public void updateFlag0ById(int uid) {
        userDao.modifyFlag0ById(uid);
    }

    @Override
    public void updateUserById(String id, String username, String email, String gender) {
        userDao.modifyUserById(id,username,email,gender);
    }
}
